<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

try {
    // 获取指定日期值班的教练列表
    $sql = "SELECT DISTINCT 
            c.id,
            c.name,
            c.avatar,
            c.gender,
            c.age,
            c.experience,
            c.description,
            c.price,
            c.rating,
            cc.name as category_name,
            GROUP_CONCAT(cs.time_slot) as available_slots
            FROM coaches c
            LEFT JOIN coach_categories cc ON c.category_id = cc.id
            INNER JOIN coach_schedules cs ON c.id = cs.coach_id 
            WHERE cs.date = ? 
            AND cs.is_available = 1 
            AND c.status = 1
            GROUP BY c.id
            ORDER BY c.rating DESC, c.experience DESC";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $coaches = [];
    while ($row = $result->fetch_assoc()) {
        // 处理教练的可用时间段
        $row['available_slots'] = $row['available_slots'] ? explode(',', $row['available_slots']) : [];
        
        // 获取教练当天已被预约的时间段
        $booked_sql = "SELECT time_slot 
                      FROM bookings 
                      WHERE coach_id = ? 
                      AND booking_date = ? 
                      AND status != 3";
        $booked_stmt = $conn->prepare($booked_sql);
        $booked_stmt->bind_param("is", $row['id'], $date);
        $booked_stmt->execute();
        $booked_result = $booked_stmt->get_result();
        
        $booked_slots = [];
        while ($booked_row = $booked_result->fetch_assoc()) {
            $booked_slots[] = $booked_row['time_slot'];
        }
        
        // 过滤掉已被预约的时间段
        $row['available_slots'] = array_values(array_diff($row['available_slots'], $booked_slots));
        
        // 只返回还有可用时间段的教练
        if (!empty($row['available_slots'])) {
            // 格式化性别显示
            $row['gender'] = $row['gender'] === '1' ? '男' : '女';
            
            // 添加教练标签
            $tags = [];
            if ($row['rating'] >= 4.8) $tags[] = '优秀教练';
            if ($row['experience'] >= 5) $tags[] = $row['experience'] . '年经验';
            $row['tags'] = $tags;
            
            $coaches[] = $row;
        }
    }
    
    echo json_encode([
        'status' => 'success',
        'list' => $coaches,
        'total' => count($coaches)
    ]);

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    if (isset($booked_stmt)) $booked_stmt->close();
    $conn->close();
}
?> 